package leetCode.sample;


import org.junit.Test;

public class AddTwoNumbersSolution {

    @Test
    public void test() {
        ListNode l1 = new ListNode(2);
        ListNode l2 = new ListNode(4);
        ListNode l3 = new ListNode(3);
        l1.next = l2;
        l2.next = l3;


        ListNode r1 = new ListNode(5);
        ListNode r2 = new ListNode(6);
        ListNode r3 = new ListNode(4);
        r1.next = r2;
        r2.next = r3;

        ListNode listNode = addTwoNumbers(l1, r1);
        System.out.println(listNode.val);
        while (listNode.next != null) {
            listNode = listNode.next;
            System.out.println(listNode.val);
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        ListNode headNode = new ListNode(0);
        ListNode currNode = headNode;
        while (l1 != null || l2 != null) {
            int left = l1 != null ? l1.val : 0;
            int right = l2 != null ? l2.val : 0;
            int sum = left + right + carry;
            int curr = sum % 10;
            carry = sum / 10;
            currNode.next = new ListNode(curr);
            currNode = currNode.next;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry > 0) {
            currNode.next = new ListNode(carry);
            currNode = currNode.next;
        }
        return headNode.next;
    }
}


class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}
